﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using forms = System.Windows.Forms;

namespace EveLogMonitor
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private List<FileMonitor> monitors = new List<FileMonitor>();

        private string filename { get; set; }

        private string filterstring { get; set; }

        public MainWindow()
        {
            InitializeComponent();
        }

        private void SelectFile(object sender, RoutedEventArgs e)
        {
            forms.OpenFileDialog fd = new forms.OpenFileDialog();
            if (fd.ShowDialog() == forms.DialogResult.OK)
            {
                filename = fd.FileName;
                fn.Text = filename;
            }
        }

        private void AddFilter(object sender, RoutedEventArgs e)
        {
            if (filename != null)
            {
                bool monitorExists = false;
                foreach (FileMonitor monitor in monitors)
                {
                    if (monitor.FilePath.Equals(filename, StringComparison.OrdinalIgnoreCase))
                    {
                        monitorExists = true;
                        if(!monitor.filterStrings.Contains(ft.Text))
                        {
                            if(ft.Text.Length>0) 
                            {
                                monitor.filterStrings.Add(ft.Text);
                                Dispatcher.Invoke((Action)delegate() { forms.MessageBox.Show("added filter"); });
                            }
                        }
                    }
                }
                // If the monitor doesn't exist, create a new one and start it.
                if (!monitorExists)
                { 
                    List<string> filterStrings = new List<string>();
                    filterStrings.Add(ft.Text);
                    SubstringFileMonitor mon = new SubstringFileMonitor(filename, filterStrings);
                    monitors.Add(mon);
                    mon.Matched += this.LineMatched;
                    mon.Start(60);
                    Dispatcher.Invoke((Action)delegate() { forms.MessageBox.Show("Started matcher"); });
                }
            }
        }

        private void LineMatched(object sender, MatchFoundEventArgs e)
        {
            Dispatcher.Invoke((Action)delegate() { forms.MessageBox.Show(String.Format("Matched filter: {0}", e.MatchedFilter));  });
        }

        private void RemoveFilter(object sender, RoutedEventArgs e)
        {

        }
    }
}
